<?php

namespace app\api\controller;
use app\common\controller\Api;


/**
 * 登录接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    private $appid='';
    private $secret='';
    public function __construct()
    {
        parent::__construct();
        $this->appid=config('site.webchat_appid');
        $this->secret=config('site.webchat_appkey');
    }

    public function login(){
        $code=$this->request->param('code');
        if(strlen($code)>3){
            $url='https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->secret.'&js_code='.$code.'&grant_type=authorization_code';
            $str=file_get_contents($url);
            $str=json_decode($str);
            if(isset($str->openid))
            {
                $info = Model('User')->find(['openid'=> $str->openid]);
                if(empty($info))
                {
                    $userInfo = input2("user_info");
                    $userInfo = json_decode(htmlspecialchars_decode($userInfo),true);
                    $data = [];
                    $data['name'] = $userInfo['name'];
                    $data['mobile'].= $userInfo['mobile'];
                    $data['openid'] = $str->openid;
                    $user_id = Model('User')->add($data);
                }else{
                    $user_id = $info['id'];
                }
                $token = $this->_get_token($user_id, $str->openid,$str->session_key);
                $this->success('登录成功',['openid' => $str->openid, 'user_id' =>$user_id, 'token' => $token]);
            }else{
                $this->error($str->errmsg);
            }
        }else{
            $this->error('请求错误');
        }
    }


    private function _get_token($user_id, $openid,$session_key)
    {
        Model('Token')->del(['user_id' => $user_id]);
        $token = md5($user_id.$session_key.TIMESTAMP);
        $data = [];
        $data['user_id'] = $user_id;
        $data['openid'] = $openid;
        $data['token'] = $token;
        $data['session_key'] = $session_key;
        Model('Token')->add($data);

        return $token;
    }
}
